/*
 * @Author: 张笑天
 * @Date: 2018-03-07 17:08:51
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-08-25 16:30:14
 */
import React from 'react';
import { routerShape } from 'react-router';
import { observer } from 'mobx-react';
import { Popover, Dropdown, Menu, Modal, message } from 'antd';
import { WeaLocaleProvider, WeaAvatar } from 'ecCom';
import CopyToClipboard from 'react-copy-to-clipboard';

import { operateUserEmailBlack } from '../../apis/setting/mailBlackList';
import { contactOperation } from '../../apis/contacts';
import AddContact from '../emailContacts/AddContact';

const MenuItem = Menu.Item;
const { confirm } = Modal;
const { getLabel } = WeaLocaleProvider;

@observer
class PopoverAccount extends React.Component {
  static contextTypes = {
    router: routerShape,
  };
  constructor(props) {
    super(props);
    this.prefixClass = 'wea-email-popover-account';
    this.id = `weaEmailPopoverAccount_${Math.random()
      .toString(36)
      .substr(2, 6)}`;
    this.isInstanceMounted = false;
    this.state = {
      addContactVisible: false, // 控制添加联系人弹窗的显隐
    };
  }
  componentDidMount() {
    this.isInstanceMounted = true;
  }
  componentWillUnmount() {
    this.isInstanceMounted = false;
  }
  hide = () => {
    this.refs.popover.refs.tooltip.setState({ visible: false });
  };
  onCopy = () => message.success(getLabel(125245, '复制成功'));
  onWriting = () => {
    const { router } = this.context;
    const { data: { typeValue, isInternal, email, type } = {} } = this.props;
    const query = {
      isInternal,
      ...(isInternal
        ? { internaltonew: JSON.stringify([{ id: typeValue, type }]) }
        : { to: email }),
    };
    router.push({
      pathname: 'main/email/new',
      query,
    });
    this.hide();
  };
  onEditContact = () => {
    const { onOperateClick, data } = this.props;
    this.hide();
    typeof onOperateClick === 'function' &&
      onOperateClick('editContact', { data });
  };
  getPopupContainer = () => document.getElementById(this.id);
  onHandleClick = ({ key, item }) => {
    const { data, onOperateClick, reloadEmail } = this.props;
    // 首先隐藏当前组件
    this.hide();
    // 根据不同的menukey执行不同的菜单动作
    if (key === 'addBlack' || key === 'delBlack') {
      const preStr =
        key === 'addBlack' ? getLabel(611, '添加') : getLabel(19133, '移出');
      confirm({
        title: getLabel(15172, '系统提示'),
        content: [
          <p>{`${getLabel(385590, '确定将')} ${
            item.props.data.email
          } ${preStr}${getLabel(385591, '黑名单吗?')}`}</p>,
          key === 'addBlack' && (
            <p>
              {getLabel(
                385592,
                '加入黑名单后，该用户发送的邮件将自动收至垃圾箱。',
              )}
            </p>
          ),
        ].filter(Boolean),
        onOk: () =>
          operateUserEmailBlack(
            key === 'addBlack'
              ? {
                  mailAddress: item.props.data.email,
                  operation: 'add',
                }
              : {
                  ids: item.props.data.backlistId,
                  operation: 'delete',
                },
          ).then((res) => {
            res.flag
              ? message.success(`${preStr}${getLabel(385593, '黑名单成功')}`)
              : message.error(
                  `${preStr}${getLabel(385594, '黑名单失败，请重试!')}`,
                );
            if (reloadEmail && typeof reloadEmail === 'function') reloadEmail();
          }),
      });
    } else if (key === 'addContact') {
      let fun =
        this.refs['popover-addContact'].addContacts ||
        this.refs['popover-addContact'].wrappedInstance.addContacts;
      fun('', (form) => {
        if (form) {
          let formitem = data.showName.replace(/[^>]*$/, ''); // 清除最后一个<>后的内容
          let nickName = formitem.match(/^.*</)[0].replace(/<$/, '').trim(); // 取昵称
          form.updateFields({
            mailUserName: nickName,
            mailAddress: data.email,
          });
        }
      });
      this.setState({ addContactVisible: true });
    } else if (key === 'delContact') {
      confirm({
        title: getLabel(15172, '系统提示'),
        content: [
          <p>{`${getLabel(385590, '确定将')} ${item.props.data.email}${getLabel(
            91,
            '删除?',
          )}`}</p>,
        ].filter(Boolean),
        okText: getLabel(826, '确定'),
        onOk: () =>
          contactOperation({
            concactIds: item.props.data.contactid,
            operation: 'deleteContact',
          }).then((res) => {
            res.flag
              ? message.success(
                  `${getLabel(572, '联系人')}${getLabel(20461, '删除成功')}`,
                )
              : message.error(
                  `${getLabel(572, '联系人')}${getLabel(20462, '删除失败')}`,
                );
            if (reloadEmail && typeof reloadEmail === 'function') reloadEmail();
          }),
      });
    }
    typeof onOperateClick === 'function' && onOperateClick(key, item);
  };
  getProps = () => {
    const {
      data,
      data: {
        showName,
        typeValue,
        isInternal,
        imageUrl,
        innerDetails,
        email,
        isContact,
        isBlacklist,
        canEdit,
      } = {},
    } = this.props;
    let headerProps = {
      name: showName || '',
      url: imageUrl || '',
      userId: typeValue || '',
    };
    return {
      ref: 'popover',
      trigger: 'click',
      overlayClassName: `${this.prefixClass}`,
      placement: 'bottomLeft',
      title: (
        <div className={`${this.prefixClass}-title`}>
          <div className={`${this.prefixClass}-title-avatar`}>
            <WeaAvatar
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaAvatar@k7520l`}
              {...headerProps}
              style={{ width: 40, height: 40 }}
            />
          </div>

          <p title={showName}>
            {isInternal
              ? showName
              : showName.substring(0, showName.indexOf('<'))}
          </p>
          <p title={isInternal ? innerDetails : email}>
            <span>{isInternal ? innerDetails : email}</span>
            {!isInternal && (
              <CopyToClipboard
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_CopyToClipboard@dii3d6`}
                text={email}
                onCopy={this.onCopy}
              >
                <a>{getLabel(77, '复制')}</a>
              </CopyToClipboard>
            )}
          </p>
        </div>
      ),
      content: (
        <div className={`${this.prefixClass}-content`} id={this.id}>
          <span
            style={{ width: canEdit ? '50%' : isInternal ? '100%' : '80%' }}
            onClick={this.onWriting}
          >
            {getLabel(81300, '写信')}
          </span>
          <span
            style={{
              display: 'none', // 等完成后再放开
              width: canEdit ? '33.3%' : isInternal ? '50%' : '40%',
              ...(!canEdit && isInternal ? { border: 'none' } : {}),
            }}
            onClick={this.hide}
          >
            {getLabel(384326, '往来邮件')}
          </span>
          {canEdit ? (
            <span
              style={{ width: '50%', border: 'none' }}
              onClick={this.onEditContact}
            >
              {getLabel(31229, '编辑联系人')}
            </span>
          ) : !isInternal ? (
            <Dropdown
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Dropdown@qrqdvs`}
              getPopupContainer={this.getPopupContainer}
              overlay={
                <Menu
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Menu@miy61g`}
                  className={`${this.prefixClass}-menu`}
                  onClick={this.onHandleClick}
                >
                  <MenuItem
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_MenuItem@l2ylck`}
                    key={`${
                      isContact === 1 || isContact === '1' ? 'del' : 'add'
                    }Contact`}
                    data={data}
                  >
                    {isContact === 1 || isContact === '1'
                      ? getLabel(91, '删除')
                      : getLabel(611, '添加')}
                    {getLabel(572, '联系人')}
                  </MenuItem>
                  <MenuItem
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_MenuItem@ng96ku`}
                    key={`${
                      isBlacklist === 1 || isBlacklist === '1' ? 'del' : 'add'
                    }Black`}
                    data={data}
                  >
                    {isBlacklist === 1 || isBlacklist === '1'
                      ? getLabel(19133, '移出')
                      : getLabel(384327, '添加到')}
                    {getLabel(31859, '黑名单')}
                  </MenuItem>
                </Menu>
              }
              trigger={['click']}
            >
              <span style={{ width: '20%' }}>
                <i className="icon-email-more" />
              </span>
            </Dropdown>
          ) : null}
        </div>
      ),
    };
  };
  onHandleAdd = () => this.setState({ addContactVisible: true });
  onHandleCancel = () => this.setState({ addContactVisible: false });
  onHandleSubmit = () => {
    if (this.props.reloadEmail && typeof this.props.reloadEmail === 'function') {
 this.props.reloadEmail(); 
}
  };
  render() {
    return [
      <Popover
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Popover@618bcm@emailpopover`}
        {...this.getProps()}
      >
        {this.props.children}
      </Popover>,
      <AddContact
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_AddContact@66n165@addcontact`}
        ref="popover-addContact"
        visible={this.state.addContactVisible}
        onHandleAdd={this.onHandleAdd}
        onCancel={this.onHandleCancel}
        onSubmit={this.onHandleSubmit}
      />,
    ];
  }
}
export default PopoverAccount;
